import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import "rxjs/add/observable/throw";

import 'rxjs/add/operator/toPromise';


@Injectable()
export class HttpService {
  local: Storage;
  constructor(
    private http: Http,) {

  }



  //get请求
  // httpGet(url: string){
  //   let headers = new Headers({'Content-Type' : 'application/json'});
  //   return this.http.get(url, headers).toPromise();
  // }


  //post
  public httpPostNoAuth(url: string, body: any) {
    let headers = new Headers({'Content-Type' : 'application/json'});
    return this.http.post(url, body, headers).toPromise();
  }



  /**
   * 处理请求中的错误，考虑了各种情况的错误处理并在 console 中显示 error
   *
   * @private
   * @param {(Response | any)} error
   * @returns
   * @memberof RestProvider
   */
  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }



  /**
   * 处理接口返回的数据，处理成 json 格式
   *
   * @private
   * @param {Response} res
   * @returns
   * @memberof RestProvider
   */
  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  /**
   * 全局获取 HTTP 请求的方法
   * @Parry
   * @private
   * @param {string} url
   * @returns {Observable<string[]>}
   * @memberof RestProvider
   */
  public httpGet(url: string): Observable<string[]> {
    return this.http.get(url)
      .map(this.extractData)
      .catch(this.handleError);
  }
}
